
cd "C:\Users/`c(username)'/Dropbox/pta_implementation/Gravity Models/"

use "PTA-Country-Year Data.dta"  , clear
keep st1 year number pta_year enter leave 
gen id =1
collapse (min) id , by(st1  enter leave number)
keep if (st1==52 & (/*number==203 |*/ number==17 | number==810)) | (number==202 | number==133) | (number==205 & (st1==316 | st1==317)) ///
  | (st1==211 & number==48) | (st1==51 & number==810) | (st1==560 & number==148) | (st1==710 & number==10) ///
  | (number==307 &(st1==670 | st1==692)) | (number==140 & st1==95) | number==346 | number==932 | number==345 | number==210
  gen hub = .
  replace hub = 1 if number==932 & st1~=750
  replace hub = 0 if number==932 & st1==750
  replace leave = 2005 if number==345
  
  
tempfile pa
save `pa'


use "PTA Design - Replication.dta" , clear
tempfile a1 a2 a3 a4 a5 a6 a7
keep st1 year stnam1 agreement number hub enter leave members
drop if number==932
preserve
keep if number==241
keep if _n==1
replace st1 = 666
replace stnam1="Israel"
replace hub=0
save `a1'
restore
preserve
keep if number==238 
keep if _n==1
replace st1 = 350
replace stnam1="Greece"
*replace hub=0
save `a2'
restore
preserve
keep if number==60
keep if _n==1
replace st1 = 212
replace stnam1="Luxembourg"
*replace hub=0
save `a3'
restore

preserve
keep if number==7
keep if _n==1
replace st1 = 710
replace stnam1="China"
replace hub=0
save `a4'
restore

preserve
keep if number==289
keep if _n==1
replace st1 = 368
replace stnam1="Lithuania"
*replace hub=0
save `a5'
restore

preserve
keep if number==43
keep if _n==1
replace st1 = 349
replace stnam1="Slovenia"
replace hub=1
replace enter = 2004
save `a6'
restore

preserve
keep if number==263
keep in 1/3
replace st1 = 305 in 1
replace stnam1="Austria" in 1
replace st1 = 375 in 2
replace stnam1="Finland" in 2
replace st1 = 380 in 3
replace stnam1="Sweden" in 3

*replace hub=1
*replace enter = 2004
save `a7'
restore

use "PTA Design - Replication.dta" , clear

keep st1 year stnam1 agreement number hub enter leave members member_count
drop if number==932 | number ==133


preserve
import excel using ptaadds.xlsx, clear first
tempfile pad
save `pad'
restore 
append using `pad'



*** corrections
replace hub = 1 if st1==395 & number==72 
replace hub = 1 if st1==385 & number==78
replace hub = 0 if st1==732 & number==78
replace hub = 1 if number==900 & st1~=145
replace hub = 0 if st1==155 & number==72
replace hub = 0 if st1==640 & number==272
replace leave = . if number==180
replace leave = 1993 if number==354
replace leave = 1995 if number==235
replace leave = 1995 if leave==1994 & number==86
replace leave = 1995 if leave==1994 & number==88
replace enter = 1995 if enter==1996 & number==248
replace enter = 1995 if enter==1996 & number==233
replace leave = 1996 if number==220
replace leave = 1986 if number==88 & st1==235 & leave==1981
replace leave = 1996 if number==312 & leave==1995
replace leave = 1981 if number==315 & leave==1980
replace st1 = 316 if st1==315 & number==68
append using `pa'
append using `a1' `a2' `a3' `a4' `a5' `a6' `a7'
gsort number -agreement
by number: replace agreement = agreement[_n-1] if agreement==""
replace agreement = "NAFTA" if number==133 & agreement==""
replace agreement="Canada-United States FTA (CUSFTA)" if number==202 & agreement==""
replace agreement="Croatia-Bosnia and Herzegovina" if number==210
 replace agreement="Slovenia-Bosnia and Herzegovina" if number==345
replace agreement="Slovenia-Croatia" if number==346
replace agreement="India-Gulf Cooperation Council" if number==932
rename hub hub1
rename enter enter1
rename leave leave1
tempfile pta1
save `pta1'
rename *1 *2
joinby  number using `pta1'
order st1 st2 stnam1 stnam2 
drop if st1==st2
drop if hub1==1 & hub2==1
egen enter = rowmax(enter1 enter2)
egen leave = rowmax(leave1 leave2)

expandcl 63 , cl(st1 st2 number) gen(exp)
drop year
sort st1 st2 number
by st1 st2 number: gen year = 1951 + _n-1
*by st1 st2 number: replace year = year[_n-1]+1 if _n>1
drop if year<enter
drop if year>=leave
drop if regexm(agreement,"\(S\)")
drop if regexm(agreement," S$")
*duplicates tag st1 st2 year , gen(tag)
gen ptanew = 1

drop  enter2 leave2 id  enter1 leave1 exp
replace number = 88 if number==89
replace number = 68 if number==64
replace number = 205 if inlist(number, 20,206,207,208)
duplicates tag st1 st2 year number, gen(tag)
drop if tag==1 & (inlist(number, 88, 68, 205))
replace agreement = "EFTA (Stockholm Convention) (G)" if agreement=="EFTA Accession of Iceland"
replace agreement = "Central European FTA (CEFTA)" if agreement=="Central European Free Trade Agreement (CEFTA) - Accession of Croatia" ///
   | agreement=="Central European FTA (CEFTA) Accession of Bulgaria" ///
   | agreement=="Central European FTA (CEFTA) Accession of Romania" ///
   | agreement=="Central European FTA (CEFTA) Accession of Slovenia" 
replace agreement = "EC Treaty" if agreement=="EC (15) Enlargement"
tempfile p pta
sort st1 st2 year 
save `pta'
collapse (max) ptanew , by(st1 st2 year)
sort st1 st2 year
save `p'


use "Gravity Rebuild.dta", clear
 
 ** Kosovo (coded as 347) drops because not in sample but probably should be recoded to 348
 ** COW has it as 347, Polity as 341 but also has Serbia and Montenegro as 347
 ** Here, Kosovo would be 348, Montenegro 341, Serbia 342, Yugoslavia 345, and Serbia and Montenegro 347 (1992-2005)
 replace st1 = 255 if st1==260 & year<1990
 replace st2 = 255 if st2==260 & year<1990
 
 sort st1 st2 year
 merge 1:1 st1 st2 year using `p'

 drop if _merge==2
 drop _merge
replace number = 88 if number==89
replace number = 68 if number==64
replace number = 205 if inlist(number, 20,206,207,208)
*replace agreement = "EFTA (Stockholm Convention) (G)" if agreement=="EFTA Accession of Iceland"

 replace ptanew = 0 if ptanew==.

xtreg imports st1_gdp st2_gdp st1_income st2_income /*colony ln_dist comcol comlang_off contig*/ i.year, fe i(dyadid_un)
estimates store m1
*keep if e(sample)
predict xbu_log, xbu /*predicted trade including dyadic component*/
gen xbu =exp(xbu_log)
predict e_log , e /*residual of trade */
gen e = exp(e_log)

reg imports st1_gdp st2_gdp st1_income st2_income colony ln_dist comcol comlang_off contig i.year,
 estimates store m2
 esttab m1 m2  using gravitytable.tex, r2 obslast starlevels(* .1 ** .05 *** .01) cells(b(star fmt(%9.2f)) se(par fmt(%9.2f))) replace
 
predict e2_log , resid

corr e_log e2_log

* imports ---> bilateral imports from st2 into st1, yr t
* imports_world ---> st1's imports from the entire world, yr t
* imports_weight ---> imports / imports_world, or the share of imports that
*                     st2 accounts for 
*
*
preserve
sort st1 st2 year
merge 1:m st1 st2 year using `pta'
*save `resid'
drop if _merge==2
drop _merge

/*
keep st1 st2 year e_log e2_log number
sort st1 st2 year
save c:/users/rhicks/dropbox/jcgray/jk/jcresiduals.dta , replace
collapse (sum) sum_e_log = e_log sum_e2_log = e2_log (mean) e_log e2_log , by(st1 number year)
sort st1 number year
save c:/users/rhicks/dropbox/jcgray/jk/jcresiduals_monadic.dta , replace
restore

/*

gen xbu_weighted_log = xbu_log*imports_weight
gen e_weighted_log = e_log * imports_weight

gen e_weighted = e * imports_weight
gen xbu_weighted= xbu*imports_weight

gen trade_bilateral = exp(imports) + exp(exports) 
gen trade_world = imports_world + exports_world
gen trade_share = trade_bilateral / trade_world
rename imports lnimports
rename exports lnexports
gen imports = exp(lnimports)
gen exports = exp(lnexports) 
gen pta_weighted = ptanew * trade_share 
xtset
gen l5tradet = (l5.trade_bilateral+l4.trade_bilateral+l3.trade_bilateral+l2.trade_bilateral+l1.trade_bilateral)/5
gen l4tradet = (l4.trade_bilateral+l3.trade_bilateral+l2.trade_bilateral+l1.trade_bilateral)/4
gen l3tradet = (l3.trade_bilateral+l2.trade_bilateral+l1.trade_bilateral)/3
gen l2tradet = (l2.trade_bilateral+l1.trade_bilateral)/2
gen l1tradet = (l1.trade_bilateral)/1


keep st1 st2 year number ptanew lnimports-e_weighted xbu_weighted pta_weighted st1_gdp st2_gdp st1_income st2_income imports exports /*polity_B polity2_B*/ ///
  st1_gdp st1_income st1_growth st2_growth l*tradet dyadid_un /*polity_A polity2_A*/
*keep if ptanew==1
rename number pnumber
drop if exports==.


compress
tempfile resid
sort st1 st2 year
merge 1:m st1 st2 year using `pta'
*save `resid'
drop if _merge==2
drop _merge
preserve
keep number year exports 
tempfile ptax
collapse (sum) exports, by(number year)
rename exports ptaX
sort number year
save `ptax'
restore
preserve
keep  st1 year number exports_world
rename st1 st2
rename exports_world partner_world
collapse (mean) partner_world , by(st2 number year)
tempfile partX
sort st2 number year
save `partX'
restore

sort number year
merge m:1 number year using `ptax'

drop if _merge==2
drop _merge

sort st2 number year
merge m:1 st2 number year using `partX'

drop if _merge==2
drop _merge


sort agreement year st1 st2
*save resid.dta , replace

*use resid.dta , clear


forval i = 1/5 {
gen l`i'trade2=l`i'tradet if year==enter
sort agreement st1 st2 year
by agreement st1 st2 : egen l`i'trade = max(l`i'trade2)
drop l`i'trade2 l`i'tradet
}

replace st1 = 818 if st1==816
replace st2 = 818 if st2==816

sort st1 st2 year
merge m:1 st1 st2 year using other/mids.dta
drop if _merge==2 
drop _merge

foreach v of varlist war- ctongoingmid {
replace `v' = 0 if `v'==.
}

preserve
use "other/alliance_v4.1_by_directed_yearly.dta" , clear
keep if year>=1970
rename ccode1 st1
rename ccode2 st2
replace st1 = 818 if st1==816
replace st2 = 818 if st2==816

gen ally = 1
collapse (sum) num_ally=ally (max) ally defense neutrality nonaggression entente , by(st1 st2 year)
tempfile ally
sort st1 st2 year
save `ally'
restore
sort st1 st2 year agreement
merge m:1 st1 st2 year using `ally'
drop if _merge==2
drop _merge

foreach v of varlist ally defense neutrality nonaggression entente num_ally {
replace `v' = 0 if `v'==.
}

preserve
use other/session_affinity_scores_un_67_02132013-polity.dta  , clear
destring _all , replace
keep statea-agree3un
compress

rename statea st1
rename stateb st2
tempfile una un
save `una'

rename st1 st2t
rename st2 st1
rename st2t st2
append using `una'
keep if year>=1970
replace st1 = 530 if st1==529 & year>1993
replace st2 = 530 if st2==529 & year>1993
compress
sort st1 st2 year
save `un'
restore

replace st1 = 347 if st1==345 & year>=1993
replace st2 = 347 if st2==345 & year>=1993
sort st1 st2 year agreement
merge m:1 st1 st2 year using `un'
drop if _merge==2 
drop _m

preserve
use "PTAs/Dispute List.dta" , clear
rename respondentID st1
rename partnerID st2
encode position, gen(posnum)
gen complainant = posnum==1
gen thirdpty = posnum==2
drop respondent partner position

collapse (sum) complainant thirdpty, by(st1 st2 year)
tempfile disp
sort st1 st2 year
save `disp'
restore
merge m:1 st1 st2 year using `disp'

drop if _merge==2 
drop _m
replace complainant = 0 if complainant==.
replace thirdpty = 0 if thirdpty==.

preserve
use other/gattlist.dta , clear
keep ccode gattjoin
rename ccode st1
rename gattjoin gattjoin1
tempfile g1 g2
sort st1 
save `g1'
rename *1 *2
sort st2
save `g2'
restore
sort st1 st2 year agreement
merge m:1 st1 using `g1'
drop if _merge==2
drop _merge

sort  st2 st1 year agreement
merge m:1 st2 using `g2'
drop if _merge==2
drop _merge

preserve
use other/wtolist.dta , clear
keep ccode wtojoin
rename ccode st1
rename wtojoin wtojoin1
replace st1 = 818 if st1==816
replace st1 = 341 if st1==348
tempfile w1 w2
sort st1 
save `w1'
rename *1 *2
sort st2
save `w2'
restore
sort st1 st2 year agreement
merge m:1 st1 using `w1'
drop if _merge==2
drop _merge

sort  st2 st1 year agreement
merge m:1 st2 using `w2'
drop if _merge==2
drop _merge

forval i = 1/2 {
gen gatt`i' = year>=gattjoin`i'
gen wto`i' = year>=wtojoin`i'
gen gattwto`i' = (gatt`i'==1 | wto`i'==1)
}
gen gattwto = gattwto1==1 & gattwto2==1

preserve
use PTAs/rta_data_full.dta , clear
decode rta, gen(agreement)
*gen agreement = rta
replace agreement = "ASEAN" if agreement=="Asean"
replace agreement="Common Makret for Eastern and Southern Africa (COMESA)" if agreement=="COMESA"
replace agreement="MERCOSUR (G)" if agreement=="Mercosur"
replace agreement="Economic Community of West African States (ECOWAS)" if agreement=="ECOWAS"
replace agreement="Central European FTA (CEFTA)" if agreement=="CEFTA"
replace agreement="Southern African Customs Union (SACU)" if agreement=="SACU"
replace agreement="Southern African Development Community (SADC)" if agreement=="SADC"
replace agreement="EFTA (Stockholm Convention) (G)" if agreement=="EFTA"
replace agreement="EC Treaty" if agreement=="EU"
replace agreement="Asia Pacific Trade Agreement (APTA)" if agreement=="Bangkok"
replace agreement="Central American Common Market CACM" if agreement=="CACM" 
replace agreement="CARICOM (G)" if agreement=="CARICOM"
replace agreement="East African Community (EAC)" if agreement=="EAC"
replace agreement="Economic and Monetary Community of Central Africa (CEMAC)" if agreement=="CEMAC"
replace agreement="European Economic Area (EEA)" if agreement=="EEA"
replace agreement="Commonwealth of Independent States (CIS)" if agreement=="CIS"
replace agreement="Latin American Integration Association LAIA" if agreement=="ALADI"
replace agreement="Melanesian Spearhead Group (MSG)" if agreement=="MSG"
replace agreement="Pacific Island Countries Trade Agreement (PICTA)" if agreement=="PICTA"
replace agreement="Pan-Arab FTA (GAFTA, PAFTA)" if agreement=="GAFTA"
replace agreement="South Pacific Regional Trade and Economic Cooperation Agreement (SPARTECA)" if agreement=="SPARTECA"
replace agreement="Gulf Cooperation Council (GCC)" if agreement=="GCC"
replace agreement="Arab Mahgreb Union" if agreement=="AMU"
replace agreement="West African Economic and Monetary Union (WAEMU)" if agreement=="UEMOA"
replace agreement = "Eurasian Economic Community (EAEC)" if agreement=="EURASEC"

replace agreement = "SAFTA" if agreement=="SAARC/SAFTA"
tempfile g
save `g'
keep if agreement =="SAFTA" 
collapse (mean) meanscore1-sdsal25 , by(agreement)
tempfile safta
save `safta'
use `g'
drop if agreement=="SAFTA"
append using `safta'
replace agreement="South Asian Free Trade Agreement" if agreement=="SAFTA"

compress
tempfile gs
sort agreement
save `gs' 
restore

merge m:1 agreement using `gs'

drop if _merge==2
drop _merge

preserve
use PTAs/haftel.dta , clear
rename rta2 agreement
replace agreement="Andean Community" if agreement=="ANDEAN"
replace agreement="Australia-New Zealand (ANZCERTA) (G)" if agreement=="ANZCERTA"
replace agreement="Common Makret for Eastern and Southern Africa (COMESA)" if agreement=="COMESA"
replace agreement="MERCOSUR (G)" if agreement=="MERCOSUR"
replace agreement="Economic Community of West African States (ECOWAS)" if agreement=="ECOWAS"
*replace agreement = "ASEAN" if agreement=="ASEAN(FTA)"
*replace agreement="Canada-United States FTA (CUSFTA)" if agreement=="NAFTA(C,US)"
*replace agreement = "Caribbean FTA (CARIFTA)" if agreement=="CARICOM(FTA)"
replace agreement="CARICOM (G)" if agreement=="CARICOM"
replace agreement="Gulf Cooperation Council" if  agreement=="GCC"
replace agreement="Central American Common Market CACM" if agreement=="CACM" | agreement=="CACM/SICA"
replace agreement="EFTA (Stockholm Convention) (G)" if agreement=="EFTA"
replace agreement="EC Treaty" if agreement=="EU"
replace agreement="Eurasian Economic Community (EAEC)" if agreement=="EAEC"
replace agreement="Arab Mahgreb Union" if agreement=="AMU"
replace agreement="Central European FTA (CEFTA)" if agreement=="CEFTA"
replace agreement="Southern African Customs Union (SACU)" if agreement=="SACU"
replace agreement="Southern African Development Community (SADC)" if agreement=="SADC"
replace agreement="West African Economic and Monetary Union (WAEMU)" if agreement=="WAEMU"
replace agreement="Latin American Integration Association LAIA" if agreement=="LAIA"
replace agreement="Asia Pacific Trade Agreement (APTA)" if agreement=="BANGKOK"
replace agreement="ECOTA" if agreement=="ECO"
replace agreement="Economic Community of the Great Lakes Nations" if agreement=="CEPGL"
replace agreement="East African Community (EAC)" if agreement=="EAC"
replace agreement="Economic and Monetary Community of Central Africa (CEMAC)" if agreement=="UDEAC"
replace agreement="South Asian Free Trade Agreement" if agreement=="SAARC" & year>=2006
replace agreement="South Asian Preferential Trade Arrangement" if agreement=="SAARC" & year<2006
tempfile haft
sort agreement year
save `haft' 
restore
merge m:1 agreement year using `haft'
tab agreement if _m==2
drop if _merge==2
drop _merge



preserve
use PTAs/haftel-impl2.dta , clear
rename rta2 agreement
replace agreement="Andean Community" if agreement=="ANDEAN"
replace agreement="Australia-New Zealand (ANZCERTA) (G)" if agreement=="ANZCERTA"
replace agreement="Common Makret for Eastern and Southern Africa (COMESA)" if agreement=="COMESA"
replace agreement="MERCOSUR (G)" if agreement=="Mercosur"
replace agreement="Economic Community of West African States (ECOWAS)" if agreement=="ECOWAS"
*replace agreement = "ASEAN" if agreement=="ASEAN(FTA)"
*replace agreement="Canada-United States FTA (CUSFTA)" if agreement=="NAFTA(C,US)"
*replace agreement = "Caribbean FTA (CARIFTA)" if agreement=="CARICOM(FTA)"
replace agreement="CARICOM (G)" if agreement=="CARICOM"
replace agreement="Gulf Cooperation Council" if  agreement=="GCC"
replace agreement="Central American Common Market CACM" if agreement=="CACM" | agreement=="CACM/SICA"
replace agreement="EFTA (Stockholm Convention) (G)" if agreement=="EFTA"
replace agreement="EC Treaty" if agreement=="EU"
replace agreement="Eurasian Economic Community (EAEC)" if agreement=="EAEC"
replace agreement="Arab Mahgreb Union" if agreement=="AMU"
replace agreement="Central European FTA (CEFTA)" if agreement=="CEFTA"
replace agreement="Southern African Customs Union (SACU)" if agreement=="SACU"
replace agreement="Southern African Development Community (SADC)" if agreement=="SADC"
replace agreement="West African Economic and Monetary Union (WAEMU)" if agreement=="WAEMU"
replace agreement="Latin American Integration Association LAIA" if agreement=="LAIA"
replace agreement="Asia Pacific Trade Agreement (APTA)" if agreement=="BANGKOK"
replace agreement="ECOTA" if agreement=="ECO"
replace agreement="Economic Community of the Great Lakes Nations" if agreement=="CEPGL"
replace agreement="East African Community (EAC)" if agreement=="EAC"
replace agreement="Economic and Monetary Community of Central Africa (CEMAC)" if agreement=="UDEAC"
replace agreement="South Asian Free Trade Agreement" if agreement=="SAARC" & year>=2006
replace agreement="South Asian Preferential Trade Arrangement" if agreement=="SAARC" & year<2006
tempfile haft2
sort agreement year
save `haft2' 
restore
merge m:1 agreement year using `haft2'
tab agreement if _m==2
drop if _merge==2
drop _merge

preserve
import excel using PTAs/Integration_Achievement_Score.xlsx, clear
drop in 1/2
replace A = "agreement" in 1
replace C = "G_S" in 1
dropmiss, force
foreach v of varlist * {
rename `v' `=lower(`v'[1])'
}
drop in 1
destring _all , replace
drop if agreement==""
replace agreement="Andean Community" if agreement=="ANCOM"
replace agreement="Australia-New Zealand (ANZCERTA) (G)" if agreement=="ANZCERTA"
replace agreement="Common Makret for Eastern and Southern Africa (COMESA)" if agreement=="COMESA"
replace agreement="MERCOSUR (G)" if agreement=="MERCOSUR"
replace agreement="Economic Community of West African States (ECOWAS)" if agreement=="ECOWAS"
replace agreement = "ASEAN" if agreement=="ASEAN(FTA)"
replace agreement="Canada-United States FTA (CUSFTA)" if agreement=="NAFTA(C,US)"
replace agreement = "Caribbean FTA (CARIFTA)" if agreement=="CARICOM(FTA)"
replace agreement="CARICOM (G)" if agreement=="CARICOM"
replace agreement="Gulf Cooperation Council" if  agreement=="GCC"
replace agreement="Central American Common Market CACM" if agreement=="CACM" | agreement=="CACM/SICA"
replace agreement="EFTA (Stockholm Convention) (G)" if agreement=="EFTA"
replace agreement="EC Treaty" if agreement=="EU"
replace agreement="Eurasian Economic Community (EAEC)" if agreement=="EAEC"
replace agreement="Economic and Monetary Community of Central Africa (CEMAC)" if agreement=="UDEAC"

tempfile fg
sort agreement year
save `fg'
restore
merge m:1 agreement year using `fg'

drop if _merge==2
drop _m

*** Now we should add in country 2 variables: 

preserve
import excel using other/p4v2012.xls, clear first
keep ccode year polity polity2
keep if year>=1970 & year<=2010
tempfile polb
rename ccode st2
rename polity polity_B
rename polity2 polity2_B
replace st2 = 345 if st2==347 & year==1992
replace st2 = 530 if st2==529 & year>=1994
sort st2 year
save `polb'
restore

sort st2 year agreement
merge m:1 st2 year using `polb'
drop if _merge==2
drop _m


 preserve
 import excel using other/wdi2014.xls , clear
 drop A D
 rename B wbcode
 rename C year
 foreach v of varlist E-U {
 label var `v' "`=`v'[1]'"
 }
 
 rename E gdpdefl
 rename F cpi
 rename G roaddensity
 rename H roads_goods
 rename I roads_paved
 rename J roads_total
 rename K imr
 rename L imr_female
 rename M imr_male
 rename N gdp_k
 rename O dgdp
 rename P gdppc_k
 rename Q fdiinflow_gdp
 rename R fdiinflow
 rename S mktcap_usd
 rename T mktcap_gdp
 rename U govdebt
 
 drop in 1
 drop gdpdefl cpi imr_female imr_male govdebt
 rename roaddensity-mktcap_gdp =_B
 destring _all , replace
ccode wbcode , from(wb) to(cow) gen(st2)
replace st2 = 341 if st2==348
replace st2 = 348 if wbcode=="KSV"
replace st2 = 342 if wbcode=="SRB" & year>=2006
replace st2 = 345 if wbcode=="SRB" & year<=1992
replace st2 = 347 if wbcode=="SRB" & year>=1993 & year<2006
replace st2 = 818 if st2==816
drop if st2==.
tempfile wdi2
sort st2 year
save `wdi2'
restore

sort st2 year
merge m:1 st2 year using `wdi2'

drop if _merge==2
drop _m

/* dyadic variables: num_ally- entente s2un-agree3un complainant thirdpty gattwto
 country 2 variables: st2_gdp st2_income st2_growth polity_B polity2_B  gattwto2
*/
drop stateaname statebname stnam1 stnam2
rename designed_institutionalization designed_instit
rename implemented_institutionalization implemented_instit
foreach v of varlist num_ally- entente complainant thirdpty gattwto gattwto2 lnimports- pta_weighted l*trade war- ctongoingmid  {
clonevar sum`v' = `v'
}
foreach v of varlist s2un-agree3un st2_gdp st2_income st2_growth polity_B polity2_B roaddensity_B-mktcap_gdp_B {
clonevar max`v' = `v'
}
foreach v of varlist * {
local `v' : variable label `v'
}
preserve
keep number agreement
gsort number -agreement 
by number: replace agreement = agreement[_n-1] if agreement=="" & agreement[_n-1]~=""
replace agreement = "Armenia-Moldova" if agreement=="Armenia-Moldvoa"
replace agreement = "United States-Bahrain" if agreement=="United Stats-Bahrain"
replace agreement="Croatia-Bosnia and Herzegovina" if number==210
replace agreement="Slovenia-Bosnia and Herzegovina" if number==345
replace agreement="Slovenia-Croatia" if number==346
replace agreement="India-Gulf Cooperation Council" if number==932
duplicates drop number agreement, force 
tempfile pn
sort number
*save pn.dta, replace
save `pn'
restore
/*
collapse (mean) enter meanscore1-sdsal25  designed_instit-lagdesscope quotasntb- lifespan st1_gdp st1_income st1_growth g_s- iavs /* polity_A polity2_A*/  ///
  lnimports- pta_weighted gattwto1 num_ally- entente complainant thirdpty gattwto l*trade   gattwto2 war- ctongoingmid ///
  s2un-agree3un st2_gdp st2_income st2_growth polity_B polity2_B roaddensity_B-mktcap_gdp_B ptaX partner_world ///
  (sum) sum* (max) max*, by(st1 number year) 

  foreach v of varlist * {
label var `v' "``v''"
}
 */ 
  
preserve
import excel using other/p4v2012.xls, clear first
keep ccode year polity polity2
keep if year>=1970 & year<=2010
tempfile pola
rename ccode st1
rename polity polity_B
rename polity2 polity2_B
replace st1 = 345 if st1==347 & year==1992
replace st1 = 530 if st1==529 & year>=1994
sort st1 year
save `pola'
restore  
 
 merge m:1 st1 year using `pola'
 
  drop if _merge==2
drop _m

preserve
use other/DPI2012.dta , clear
keep countryname ifs year yrsoffc finittrm yrcurnt execrlc prtyin checks
ccode ifs , from(wb) to(cow) gen(ccode)
replace ccode = 680 if countryname=="Yemen (PDR)"
replace ccode = 345 if countryname=="Yugoslavia"
replace ccode = 365 if ccode==364
*replace ccode = 260 if ccode==255 
 drop if ccode==.
 rename ccode st1
 replace st1 = 347 if st1==345 & year>=1993
 replace st1 = 818 if st1==816

 tempfile dpi
 sort st1 year
 save `dpi'
 restore
 sort st1 year
 merge m:1 st1 year using `dpi'

 *** 
 drop if _merge==2
drop _merge

preserve
use other/polcon2012.dta , clear
keep if year>=1970
replace ccode = 347 if ctrynm=="YGS" & ccode==.
drop if ccode==.
keep ccode year polconiii  legfra*
rename ccode st1
replace st1 = 530 if st1==529 & year>1993
tempfile vp 
sort st1 year
save `vp'
restore
replace st1 = 342 if st1==347 & year>=2006
sort st1 year
 merge m:1 st1 year using `vp'
drop if _merge==2
drop _merge
 
 preserve
 import excel using other/wdi2014.xls , clear
 drop A D
 rename B wbcode
 rename C year
 foreach v of varlist E-U {
 label var `v' "`=`v'[1]'"
 }
 
 rename E gdpdefl
 rename F cpi
 rename G roaddensity
 rename H roads_goods
 rename I roads_paved
 rename J roads_total
 rename K imr
 rename L imr_female
 rename M imr_male
 rename N gdp_k
 rename O dgdp
 rename P gdppc_k
 rename Q fdiinflow_gdp
 rename R fdiinflow
 rename S mktcap_usd
 rename T mktcap_gdp
 rename U govdebt
 
 drop in 1
 destring _all , replace
ccode wbcode , from(wb) to(cow) gen(st1)
replace st1 = 341 if st1==348
replace st1 = 348 if wbcode=="KSV"
replace st1 = 342 if wbcode=="SRB" & year>=2006
replace st1 = 345 if wbcode=="SRB" & year<=1992
replace st1 = 347 if wbcode=="SRB" & year>=1993 & year<2006
replace st1 = 818 if st1==816
drop if st1==.
tempfile wdi
sort st1 year
save `wdi'
restore

sort st1 year
merge m:1 st1 year using `wdi'

drop if _merge==2
drop _merge
preserve
import excel using other/wdi2014_xr.xls , clear
drop A D
rename B wbcode
rename C indname
foreach v of varlist E-BF {
rename `v' yr`=`v'[1]'
}
reshape long yr , i(wbcode indname) j(year)
levelsof indname if  regexm(indname,"^Official") , local(j) clean
replace indname = "XR" if regexm(indname,"^Official")
levelsof indname if  regexm(indname,"^Real") , local(k) clean
replace indname = "REER" if regexm(indname,"^Real")
reshape wide yr , i(wbcode year) j(indname) string
destring _all , replace
rename yr* *
label var REER "`k'"
label var XR "`j'"
ccode wbcode , from(wb) to(cow) gen(st1)
replace st1 = 341 if st1==348
replace st1 = 348 if wbcode=="KSV"
replace st1 = 342 if wbcode=="SRB" & year>=2006
replace st1 = 345 if wbcode=="SRB" & year<=1992
replace st1 = 347 if wbcode=="SRB" & year>=1993 & year<2006
replace st1 = 818 if st1==816
drop if st1==.

tempfile xrw
sort st1 year
save `xrw'
restore

sort st1 year
merge m:1 st1 year using `xrw'

drop if _merge==2
drop _merge

preserve
foreach m of newlist imf fine coarse {
insheet using other/era_`m'.csv , comma clear
qui {
drop in 1/4
rename v1 year
unab v: v*
foreach i of local v {
replace `i' =subinstr(`i',".","_",.) if _n==1
replace `i' =subinstr(`i'," ","_",.) if _n==1
replace `i' =subinstr(`i',",","_",.) if _n==1
replace `i' =subinstr(`i',"'","_",.) if _n==1
replace `i' =subinstr(`i',"-","_",.) if _n==1
local n =`i'[1]
rename `i' c`n'
}
drop in 1
destring _all , replace
drop if year==.
reshape long c , i(year) j(country) str
rename c XR_`m'

drop if year<1960
drop if XR_`m'==.
replace country = subinstr(country,"_"," ",.)
replace country = "Antigua and Barbuda" if country=="Antigua Barb"
replace country = "Bosnia And Herzegovina" if country=="Bosnia Herzeg"
replace country = "Cayman Islands" if country=="Cayman Is"
replace country = "Central African Republic" if country=="CAR"
replace country = "Cote D'Ivoire" if country=="Cote D Ivoire"
replace country = "Czech Republic" if country=="Czech Rep"
replace country = "Czechoslovakia" if country=="Czechoslovak"
replace country = "Congo, Rep." if country=="Congo  Rep " | country=="Congo  Rep"
replace country = "Congo, Dem. Rep." if country=="Congo  Dem " | country=="Congo  Dem"
replace country = "Dominican Republic" if country=="Dominican Rep"
replace country = "Equatorial Guinea" if country=="Equat Guinea"
replace country = "Faroe Islands" if country=="Faeroe Is"
replace country = "French Guiana" if country=="French Guyana"
replace country = "French Polynesia" if country=="French Poly"
replace country = "East Germany" if country=="Germany East"
replace country = "Guinea-Bissau" if country=="Guinea Bissau"
replace country = "North Korea" if country=="Korea  North"
replace country = "Kyrgyz Republic" if country=="Kyrgyz Rep"
replace country = "Laos" if country=="Lao"
replace country = "Marshall Islands" if country=="Marshall Is"
replace country = "Northern Mariana Islands" if country=="N Mariana Is"
replace country = "Papua New Guinea" if country=="Papua New G "
replace country = "Sao Tome And Principe" if country=="Sao Tome Pr"
replace country = "Slovakia" if country=="Slovak Rep"
replace country = "Solomon Islands" if country=="Solomon Is"
replace country = "St. Kitts And Nevis" if country=="St Kitts N"
replace country = "St. Lucia" if country=="St Lucia"
replace country = "St. Vincent And The Grenadines" if country=="St Vincent Gr"
replace country = "Trinidad And Tobago" if country=="Trinidad Tob"
replace country = "Turks and Caicos" if country=="Turks and C"
replace country = "United Arab Emirates" if country=="UAE"
replace country = "United Kingdom" if country=="UK"
replace country = "United States" if country=="US"
replace country = "South Korea" if country=="Korea"
replace country = "Vietnam" if country=="Viet Nam"
replace country = "Yemen, Rep." if country=="Yemen"
replace country = "West Bank and Gaza" if country=="West Bank G"

ccode country, from(cty) to(cow) gen(st1)
replace st1 = 341 if country=="Montenegro"
replace st1 = 342 if country=="Serbia"
replace st1= 818 if st1==816
}
compress
tempfile xr`m'
sort st1 year
save `xr`m''

}
restore
sort st1 year
merge m:1 st1 year using `xrfine' ,
 *tab st1 if _m==1 & year<2008
 
drop if _merge==2
drop _merge

sort st1 year
merge m:1 st1 year using `xrimf' , 

drop if _merge==2
drop _merge

sort st1 year
merge m:1 st1 year using `xrcoarse' , 
drop if _merge==2
drop _merge

drop country wbcode countryname ifs

label var gattwto1 "Country 1 in GATT/WTO"
label var gattwto2 "Proportion of partner countries in GATT/WTO"
label var sumgattwto2 "Number of partner countries in GATT/WTO"
label var g_s "Free movement of goods and services - IAS"
label var cap "Free movement of capital - IAS"
label var lab "Free movement of labor - IAS"
label var si "Supranational institutions - IAS"
label var mc "Monetary coordination - IAS"
label var fc "Fiscal coordination - IAS"
label var ias "Integration achievement score - IAS"
label var iavs "IAS (component squared then sqrt of sum) - IAS"
label var imports_world "Country 1's imports to world"
label var exports_world "Country 1's exports from world"
label var sumnum_ally "Total number of alliances with PTA partners - COW"
 label var sumally "Number of PTA partners country allied with - COW"
 label var sumdefense "Number of PTA partners country has defense pact with - COW"
 label var sumneutrality "Number of PTA partners country has neutrality pact with - COW"
 label var sumnonaggression "Number of PTA partners country has nonaggression pact with - COW"
 label var sumentente "Number of PTA partners country has entente pact with - COW"
 label var sumally "Number of PTA partners country allied with - COW"

label var XR_imf "IMF's XR classification - from Reinhart & Rogoff"
label var XR_fine "R&R's fine XR classification"
label var XR_coarse "R&R's coarse XR classification"
label var num_ally "Average number of alliances with PTA partners"
label var ally "Average number of PTA partners country allied with"
label var defense "Average number of PTA partners country has defense pact with"
label var neutrality "Average number of PTA partners country has neutrality pact  with"
label var nonaggression "Average number of PTA partners country has nonaggression pact  with"
label var entente "Average number of PTA partners country has entente pact with"

label var s2un "Average affinity index with PTA partners (2-category vote)"
label var s3un "Average affinity index with PTA partners (3-category vote)"
label var agree2un "Average voting similarity index with PTA partners (2-category vote)"
label var agree3un "Average voting similarity index with PTA partners (3-category vote)"

label var maxs2un "Maximum affinity index of PTA partners (2-category vote)"
label var maxs3un "Maximum affinity index of PTA partners (3-category vote)"
label var maxagree2un "Maximum voting similarity index of PTA partners (2-category vote)"
label var maxagree3un "Maximum voting similarity index of PTA partners (3-category vote)"
label var complainant "Average number of cases PTA partner is complainant in case"
label var thirdpty "Average number of cases PTA partner is third party in case"
label var sumcomplainant "Total number of cases PTA partner is complainant in case"
label var sumthirdpty "Total number of cases PTA partner is third party in case"

label var sumgattwto "Number of GATT dyads in PTA"
label var gattwto "Proportion of GATT dyads in PTA"
foreach v of varlist maxst2_gdp- maxmktcap_gdp_B {
label var `v' "Max `: var label `v'' of PTA partners"
}
foreach v of varlist st2_gdp- mktcap_gdp_B {
label var `v' "Average `: var label `v'' of PTA partners"
}

label var lnimports "Imports from st2 into st1 (logged)"
label var lnexports "Exports from st1 to st2 (logged)"
label var imports "Imports from st2 into st1 (nonlogged)"
label var exports "Exports from st1 to st2 (nonlogged)"

label var xbu_log "Trade prediction + dyadic FE  (logged)"
label var xbu "Trade prediction + dyadic FE (nonlogged)"
label var e_log "Residuals (logged)"
label var e "Residuals (nonlogged)"
label var xbu_weighted_log "Trade prediction (logged) weighted by import share"
label var e_weighted_log "Residual (logged) weighted by import share"
label var e_weighted "Residual weighted by import share"
label var xbu_weighted "Trade prediction weighted by import share"
label var pta_weighted "PTAs share of country 1's world trade (M+X)"

label var ptaX "Sum of intra-PTA exports"
label var partner_world "Sum of PTA partners' X to world"
label var sumxbu "Sum of trade prediction + dyadic FE (nonlogged)"
label var sume "Sum of Residuals (nonlogged)"
label var sume_weighted "Sum of residual weighted by import share"
label var sumxbu_weighted "Sum of trade prediction (logged) weighted by import share"
label var sumimports "Sum of country 1's imports from PTA (nonlogged)"
label var sumexports "Sum of country 1's exports to PTA (nonlogged)"

label var war "Average number of wars between cty1 and PTA partners in year"
label var waronset "Average number of wars initiated between cty1 and PTA partners in year"
label var midonset "Average number of MIDs initiated between cty1 and PTA partners in year"
label var ongoingmid "Average number of MIDs between cty1 and PTA partners in year"
label var sumwar "Summed number of wars between cty1 and PTA partners in year"
label var sumwaronset "Summed number of wars initiated between cty1 and PTA partners in year"
label var summidonset "Summed number of MIDs initiated between cty1 and PTA partners in year"
label var sumongoingmid "Summed number of MIDs between cty1 and PTA partners in year"

label var ctwar "Average number of total wars between cty1 and PTA partners in year"
label var ctwaronset "Average number of total wars initiated between cty1 and PTA partners in year"
label var ctmidonset "Average number of total MIDs initiated between cty1 and PTA partners in year"
label var ctongoingmid "Average number of total MIDs between cty1 and PTA partners in year"
label var sumctwar "Summed number of total wars between cty1 and PTA partners in year"
label var sumctwaronset "Summed number of total wars initiated between cty1 and PTA partners in year"
label var sumctmidonset "Summed number of total MIDs initiated between cty1 and PTA partners in year"
label var sumctongoingmid "Summed number of total MIDs between cty1 and PTA partners in year"

sort dyadid year
by dyadid  : gen ptastart2 = ptanew==1 & l.ptanew==0
by dyadid : gen prepta_et = l.e_log if ptastart2==1
by dyadid : egen prepta_e=max(prepta_et)
by dyadid  : replace prepta_e = e_log[1] if prepta_e==.


/*
compress
sort st1 st2 year
save fullgrav.dta , replace
*/
keep if ptanew==1
foreach v of varlist * {
local `v' : variable label `v'
}
collapse (mean) enter meanscore1-sdsal25  designed_instit-lagdesscope quotasntb- lifespan st1_gdp st1_income st1_growth g_s- iavs /* polity_A polity2_A*/  ///
  lnimports- pta_weighted gattwto1 num_ally- entente complainant thirdpty gattwto l*trade   gattwto2 war- ctongoingmid ///
  s2un-agree3un st2_gdp prepta_e st2_income st2_growth polity_B polity2_B roaddensity_B-mktcap_gdp_B ptaX partner_world polconiii  legfra*  yrsoffc finittrm yrcurnt execrlc prtyin checks ///
  (sum) sum* (max) max*, by(st1 number year) 

  foreach v of varlist * {
label var `v' "``v''"
}
  



forval i = 1/5 {
label var l`i'trade "Average trade with PTA partners in `i' yrs before PTA"
label var suml`i'trade "Summed trade with PTA partners in `i' yrs before PTA"
}

gen X_ptashare = sumexports/ptaX
gen X_partnershare = sumexports/partner_world
label var X_ptashare "Country 1's exports as share of intra-PTA exports"
label var X_partnershare "Country 1's exports as share of partners' world X"
drop sumimports_world sumexports_world sumptanew sumxbu_log sume_log sumxbu_weighted_log sume_weighted_log sumpta_weighted sumimports_weight

sort number st1 year
merge m:1 number using `pn'
drop _merge


compress
sort st1 year number 
saveold C:\Users\rhicks\Dropbox\jcgray\jk\monadic_vRLB.dta , replace

gen state_pta = st1*1000 + number
keep state_pta year prepta_e
sort state_pta year

saveold "C:\Users\rhicks\Dropbox\jcgray\jk\implvar_mean_vRLB.dta",  replace
